<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人设置</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="个人信息" name="info">
          <el-form 
            :model="userForm" 
            :rules="rules" 
            ref="userFormRef" 
            label-width="100px" 
            class="profile-form"
          >
            <el-form-item label="头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                action="/api/user/upload-avatar"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            
<!--            <el-form-item label="用户名" prop="username">-->
<!--              <el-input v-model="userForm.username" disabled />-->
<!--            </el-form-item>-->
<!--            -->
<!--            <el-form-item label="姓名" prop="realName">-->
<!--              <el-input v-model="userForm.realName" />-->
<!--            </el-form-item>-->
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
<!--            -->
<!--            <el-form-item label="地址" prop="address">-->
<!--              <el-input v-model="userForm.address" type="textarea" :rows="2" />-->
<!--            </el-form-item>-->
            
            <el-form-item>
              <el-button type="primary" @click="submitUserInfo">保存信息</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="修改密码" name="password">
          <el-form 
            :model="passwordForm" 
            :rules="passwordRules" 
            ref="passwordFormRef" 
            label-width="120px" 
            class="password-form"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
<!--        <el-tab-pane label="消息通知" name="notification">-->
<!--          <el-form :model="notificationForm" label-width="120px" class="notification-form">-->
<!--            <el-form-item label="订单通知">-->
<!--              <el-switch v-model="notificationForm.orderNotification" />-->
<!--            </el-form-item>-->
<!--            -->
<!--            <el-form-item label="系统通知">-->
<!--              <el-switch v-model="notificationForm.systemNotification" />-->
<!--            </el-form-item>-->
<!--            -->
<!--            <el-form-item label="短信通知">-->
<!--              <el-switch v-model="notificationForm.smsNotification" />-->
<!--            </el-form-item>-->
<!--            -->
<!--            <el-form-item label="邮件通知">-->
<!--              <el-switch v-model="notificationForm.emailNotification" />-->
<!--            </el-form-item>-->
<!--            -->
<!--            <el-form-item>-->
<!--              <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>-->
<!--            </el-form-item>-->
<!--          </el-form>-->
<!--        </el-tab-pane>-->
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userAPI } from '@/api/api'

// 激活的标签页
const activeTab = ref('info')

// 用户表单数据
const userForm = reactive({
  avatar: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  address: ''
})

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 通知设置表单
const notificationForm = reactive({
  orderNotification: true,
  systemNotification: true,
  smsNotification: false,
  emailNotification: false
})

// 表单验证规则
const rules = {
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const userFormRef = ref(null)
const passwordFormRef = ref(null)

// 获取上传头像所需的headers
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token') || ''}`
}

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await userAPI.getUserInfo()
    if (response.code === 200) {
      const { data } = response
      userForm.avatar = data.avatar || ''
      userForm.username = data.username
      userForm.realName = data.realName
      userForm.phone = data.phone
      userForm.email = data.email
      userForm.address = data.address
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 获取通知设置
const getNotificationSettings = async () => {
  try {
    const response = await userAPI.getNotificationSettings()
    if (response.code === 200) {
      const { data } = response
      notificationForm.orderNotification = data.orderNotification
      notificationForm.systemNotification = data.systemNotification
      notificationForm.smsNotification = data.smsNotification
      notificationForm.emailNotification = data.emailNotification
    }
  } catch (error) {
    console.error('获取通知设置出错:', error)
  }
}

// 提交用户信息
const submitUserInfo = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await userAPI.updateUserInfo(userForm)
        if (response.code === 200) {
          ElMessage.success('个人信息更新成功')
        } else {
          ElMessage.error(response.message || '个人信息更新失败')
        }
      } catch (error) {
        console.error('更新用户信息出错:', error)
        ElMessage.error('网络错误，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await userAPI.changePassword(passwordForm)
        if (response.code === 200) {
          ElMessage.success('密码修改成功')
          resetPasswordForm()
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码出错:', error)
        ElMessage.error('网络错误，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 保存通知设置
// const saveNotificationSettings = async () => {
//   try {
//     const response = await userAPI.updateNotificationSettings(notificationForm)
//     if (response.code === 200) {
//       ElMessage.success('通知设置已保存')
//     } else {
//       ElMessage.error(response.message || '保存通知设置失败')
//     }
//   } catch (error) {
//     console.error('保存通知设置出错:', error)
//     ElMessage.error('网络错误，请稍后重试')
//   }
// }

// 头像上传前的校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功的回调
// eslint-disable-next-line no-unused-vars
const handleAvatarSuccess = (response, _file) => {
  if (response.code === 200) {
    userForm.avatar = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 重置表单
const resetForm = () => {
  userFormRef.value?.resetFields()
  getUserInfo()
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
}

// 组件挂载时获取用户信息和通知设置
onMounted(() => {
  getUserInfo()
  getNotificationSettings()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 900px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form, .password-form, .notification-form {
  max-width: 600px;
  margin: 20px auto;
}

.avatar-uploader {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 50%;
}
</style> 